﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace SocialKit.LightRest
{
    /// <summary>
    /// Represents a url encoded form.
    /// </summary>
    public class HttpUrlEncodedForm : Collection<KeyValuePair<string, string>>, IHttpContentCreator
    {
        /// <summary>
        /// Initialize a new instance of SocialKit.LightRest.HttpUrlEncodedForm class.
        /// </summary>
        public HttpUrlEncodedForm() { }

        /// <summary>
        /// Initialize a new instance of SocialKit.LightRest.HttpUrlEncodedForm class.
        /// </summary>
        /// <param name="initialValues">The initial values.</param>
        public HttpUrlEncodedForm(IEnumerable<KeyValuePair<string, string>> initialValues)
        {
            if (initialValues != null)
            {
                foreach (var p in initialValues)
                {
                    this.Add(p);
                }
            }
        }

        /// <summary>
        /// Add a name and value into this form.
        /// </summary>
        /// <param name="name">The name of data.</param>
        /// <param name="value">The value of data.</param>
        public void Add(string name, string value)
        {
            this.Add(new KeyValuePair<string, string>(name, value));
        }

        /// <summary>
        /// Append a name and value into this form then returns this form.
        /// </summary>
        /// <param name="name">The name of data.</param>
        /// <param name="value">The value of data.</param>
        /// <returns>The current form.</returns>
        public HttpUrlEncodedForm Append(string name, string value)
        {
            this.Add(name, value);

            return this;
        }

        Encoding contentEncoding;

        #region IHttpContentCreator Members

        /// <summary>
        /// Gets or sets the encoding of the content of this form.
        /// </summary>
        public Encoding ContentEncoding
        {
            get
            {
                if (contentEncoding == null)
                    contentEncoding = Encoding.UTF8;

                return this.contentEncoding;
            }

            set { this.contentEncoding = value; }
        }

        /// <summary>
        /// Gets a string value indicates the content type of this form.
        /// </summary>
        public string ContentType
        {
            get { return "application/x-www-form-urlencoded"; }
        }

        /// <summary>
        /// Create a byte array of this form.
        /// </summary>
        /// <returns></returns>
        public byte[] CreateContent()
        {
            return ContentEncoding.GetBytes(this.ToQueryString());
        }

        #endregion
    }
}